package com.bwie.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bwie.pojo.User;
import com.bwie.service.UserService;
import com.bwie.util.R;
import com.bwie.vo.UserVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author 国兴越
 * @version 1.0
 * Create by
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    UserService userService;


    @Autowired
    StringRedisTemplate stringRedisTemplate;



    @PostMapping("/login")
    public R login(@RequestBody UserVo userVo){

        User user = userService.getOne(new QueryWrapper<User>().lambda().eq(User::getAccount, userVo.getAccount()));
        if(user==null){
            return R.error().message("改账号不存在");
        }

        if(StringUtils.isEmpty(userVo.getAccount())){
            return R.error().message("账号不能为空");
        }
        if(StringUtils.isEmpty(userVo.getPwd())){
            return R.error().message("密码为空");
        }

        if(!userVo.getPwd().equals(user.getPwd())){
            return R.error().message("密码输入错误");
        }

        stringRedisTemplate.opsForValue().set("role", String.valueOf(user.getRole()),15, TimeUnit.MINUTES);
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "bwie").claim("id", user.getId()).claim("role", user.getRole()).setIssuedAt(new Date()).compact();




        return R.ok().message("登录成功").data("token",token);


    }











}
